﻿using FirstLimitUpMode.Data;
using FirstLimitUpMode.Handles;
using FirstLimitUpMode.Views;
using GpCommon.Helpers;
using GpCommon.Logger;
using GpCommon.Models;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace FirstLimitUpMode.ViewModels
{
    internal class GpDetailInfoVModel : BindableBase
    {
        public GpDetailInfoView _view;
        private string _code;
        private float _mark97;
        private bool _isTopBuy;
        private int _formula = 0;
        private string _mainNotion;
        private string _NotionRank;
        private SynchronizationContext _synContent = null;

        private GpCurEntity m_CurEntity;
        /// <summary>
        /// 详细信息实体
        /// </summary>
        public GpCurEntity CurEntity
        {
            get { return m_CurEntity; }
            set 
            { 
                m_CurEntity = value; 
                RaisePropertyChanged(nameof(CurEntity));
            }
        }
        private int m_BuyInCount = 0;
        /// <summary>
        /// 下单股数
        /// </summary>
        public int BuyInCount
        {
            get { return m_BuyInCount; }
            set
            {
                m_BuyInCount = value;
                //BuyInValue = m_BuyInCount * CurEntity.TopPrice;
                RaisePropertyChanged(nameof(BuyInCount));
            }
        }
        private float m_BuyInValue;
        /// <summary>
        /// 下单金额
        /// </summary>
        public float BuyInValue
        {
            get { return m_BuyInValue; }
            set
            {
                m_BuyInValue = value;
                RaisePropertyChanged(nameof(BuyInValue));
            }
        }

        private ImageSource m_PreHourImage;
        /// <summary>
        /// 分时
        /// </summary>
        public ImageSource PreHourImage
        {
            get { return m_PreHourImage; }
            set
            {
                m_PreHourImage = value;
                RaisePropertyChanged(nameof(PreHourImage));
            }
        }
        private ImageSource m_PreDayImage;
        /// <summary>
        /// 日线
        /// </summary>
        public ImageSource PreDayImage
        {
            get { return m_PreDayImage; }
            set
            {
                m_PreDayImage = value;
                RaisePropertyChanged(nameof(PreDayImage));
            }
        }


        public ICommand AddLockCommand { get; set; }
        public ICommand RemoveLockCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand BuyInCommand { get; set; }
        public ICommand SaleOutCommand { get; set; }

        public ICommand UpCommand { get; set; }
        public ICommand DownCommand { get; set; }

        public GpDetailInfoVModel(GpDetailInfoView view, string code, float mark97, bool isTopBuy)
        {
            _view = view;
            _code = code;
            _mark97 = mark97;
            _isTopBuy = isTopBuy;
            _synContent = SynchronizationContext.Current;

            InitCommand();

            bool isFirst = true;
            Task.Run(() =>
            {
                Stopwatch stopwatch = new Stopwatch();
                while (_view != null)
                {
                    try
                    {
                        stopwatch.Restart();

                        GetData(ref isFirst);
                        BindHourImage();
                        BindDayImage();



                        while (stopwatch.ElapsedMilliseconds < 1000)
                        {
                            Thread.Sleep(500);
                        }
                    }
                    catch (Exception ex)
                    {

                    }
                }
            });
        }

        private void InitCommand()
        {
            AddLockCommand = new DelegateCommand(AddLockExecute);
            RemoveLockCommand = new DelegateCommand(RemoveLockExecute);
            DeleteCommand = new DelegateCommand(DeleteExecute);
            BuyInCommand = new DelegateCommand(BuyInExecute);
            SaleOutCommand = new DelegateCommand(SaleOutExecute);
            UpCommand = new DelegateCommand(UpExecute);
            DownCommand = new DelegateCommand(DownExecute);
        }
        private void InitData()
        {
            var notions = GpNetDataHelper.GetGpNotionByCode(_code).Result;
            if (notions.Count > 0)
            {
                var notionRank = GpNetDataHelper.GetNotionRank().Result;
                foreach (var item in notions)
                {
                    var mainNotion = notionRank.FirstOrDefault(x => x.Code == item);
                    if (mainNotion != null)
                    {
                        _mainNotion += mainNotion.Name + $"({(notionRank.IndexOf(mainNotion) + 1) + "/" + notionRank.Count})" + "   ";
                    }
                }
                _view.Dispatcher.Invoke(new Action(() =>
                {
                    foreach (var item in notions)
                    {
                        var mainNotion = notionRank.FirstOrDefault(x => x.Code == item);
                        if (mainNotion != null)
                        {
                            TextBlock newTextBlock = new TextBlock();

                            // 设置TextBlock的属性
                            newTextBlock.Text = mainNotion.Name + $"({(notionRank.IndexOf(mainNotion) + 1) + "/" + notionRank.Count})";
                            newTextBlock.FontSize = 12;
                            newTextBlock.Margin = new Thickness(5, 0, 10, 0);
                            newTextBlock.Background = notionRank.IndexOf(mainNotion) + 1 <= 20 ? Brushes.Red : Brushes.White;
                            _view.MainNationPanel.Children.Add(newTextBlock);


                        }
                    }
                }));
                //var mainNotion = notionRank.FirstOrDefault(x => x.Code == notions[0]);
                //if (mainNotion != null)
                //{
                //    var members = GpNetDataHelper.GetNotionMembersByCode(mainNotion.Code, mainNotion.TotalCount).Result;
                //    var topCount = members.FindAll(x => IsTop(x)).Count;
                //    _mainNotion = mainNotion.Name + $"({topCount})";
                //    _NotionRank = (notionRank.IndexOf(mainNotion) + 1) + "/" + notionRank.Count;
                //}
            }
        }
        #region 私有方法

        private bool IsTop(GpCurEntity ent)
        {
            float offset = 0.1f;
            if (ent.Name.Contains("ST"))
            {
                offset = 0.05f;
            }
            else if(ent.Code.StartsWith("60")
                || ent.Code.StartsWith("00"))
            {
                offset = 0.1f;
            }
            else if(ent.Code.StartsWith("68")
                || ent.Code.StartsWith("30"))
            {
                offset = 0.2f;
            }
            else if (ent.Code.StartsWith("8"))
            {
                offset = 0.3f;
            }
            double topOffset = Math.Round(ent.YesClsPrice * offset, 2, MidpointRounding.AwayFromZero);
            var maxValue = Math.Round(topOffset / ent.YesClsPrice * 100, 2, MidpointRounding.AwayFromZero);

            if (ent.CurMarkUp < maxValue)
                return false;
            return true;
        }
        private void GetData(ref bool isFirst)
        {
            try
            {
                List<SectorEntity> sectors = GpNetDataHelper.GetSectorRank().Result;
                var curSecotrId = GpNetDataHelper.GetGpSector(_code).Result; 
                var tempCutEnt = GpNetDataHelper.GetGpCurInfoByCode(_code).Result;
                if (sectors == null || sectors.Count == 0 || string.IsNullOrEmpty(curSecotrId) || tempCutEnt == null)
                    return;
                var index = sectors.FindIndex(x => x.SectorId == curSecotrId);
                if (index >= 0)
                {
                    tempCutEnt.Sector = sectors[index].SectorName + $"({(index + 1) + "/" + sectors.Count})";
                    //tempCutEnt.SectorRank = (index + 1) + "/" + sectors.Count;
                }
                if (isFirst)
                {
                    InitData();
                    if (tempCutEnt.TopPrice > 0)
                    {
                        BuyInCount = (int)(TempData.CurValue / 100 / tempCutEnt.TopPrice) * 100;
                        BuyInValue = m_BuyInCount * tempCutEnt.TopPrice;
                    }
                    isFirst = false;
                }
                tempCutEnt.MainNotion = _mainNotion;
                tempCutEnt.NotionRank = _NotionRank;
                CurEntity = tempCutEnt;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
        private void BindHourImage()
        {
            string uri = UrlHelper.GetUrlForHourLineImage(_code);

            BitmapImage bitmap = new BitmapImage();
            using (var webClient = new WebClient())
            {
                byte[] imageBytes = webClient.DownloadData(uri);
                using (var ms = new MemoryStream(imageBytes))
                {
                    bitmap.BeginInit();
                    bitmap.StreamSource = ms;
                    bitmap.CacheOption = BitmapCacheOption.OnLoad; // 这个选项很重要，它告诉WPF立即加载图像数据
                    bitmap.EndInit();
                    bitmap.Freeze();
                }
            }
            PreHourImage = bitmap;
        }
        private void BindDayImage()
        {
            string uri = UrlHelper.GetUrlForDayLineImage(_code, _formula);
            BitmapImage bitmap = new BitmapImage();
            using (var webClient = new WebClient())
            {
                byte[] imageBytes = webClient.DownloadData(uri);
                using (var ms = new MemoryStream(imageBytes))
                {
                    bitmap.BeginInit();
                    bitmap.StreamSource = ms;
                    bitmap.CacheOption = BitmapCacheOption.OnLoad; // 这个选项很重要，它告诉WPF立即加载图像数据
                    bitmap.EndInit();
                    bitmap.Freeze();
                }
            }
            PreDayImage = bitmap;
        }
        #endregion

        #region 命令执行方法
        private void AddLockExecute()
        {
            if (!TempData.LockList.Contains(_code))
            {
                TempData.LockList.Add(_code);
                TempData.WriteLockGps();
            }
        }
        private void RemoveLockExecute()
        {
            if (TempData.LockList.Contains(_code))
            {
                TempData.LockList.Remove(_code);
                TempData.WriteLockGps();
            }
            _view.Close();
        }
        private void DeleteExecute()
        {
            if (!TempData.RemoveList.Contains(_code))
            {
                TempData.RemoveList.Add(_code);
            }
            _view.Close();
        }
        private void BuyInExecute()
        {
            this._view.Close();
            if (!TempData.OrderToBuyList.Contains(_code))
                TempData.OrderToBuyList.Add(_code);
            if (_isTopBuy)
            {
                AutoHelper.BuyExecute(_code, CurEntity.TopPrice - 0.01, CurEntity.TopPrice, BuyInCount);
            }
            else
            {
                double price97 = CommonUtility.RoundUp(CurEntity.YesClsPrice * (1 + _mark97 / 100.0), 2);
                AutoHelper.BuyExecute(_code, price97, CurEntity.TopPrice, BuyInCount);
            }
        }

        private void SaleOutExecute()
        {
            this._view.Close();
            if (!TempData.OrderToSaleList.Contains(_code))
                TempData.OrderToSaleList.Add(_code);

            AutoHelper.SaleExecute(_code, CurEntity.TopPrice - 0.01, CurEntity.TopPrice * 0.985, 0, true);
        }
        private void UpExecute()
        {
            BuyInCount += 100;
            BuyInValue = m_BuyInCount * CurEntity.TopPrice;
        }
        private void DownExecute()
        {
            if (BuyInCount <= 0)
                return;
            BuyInCount -= 100;
            BuyInValue = m_BuyInCount * CurEntity.TopPrice;

        }

        #endregion
    }
}
